import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from "@/utils/auth";
import Login from "@/api/login";
import defAva from "@/assets/images/default.jpg";

interface UserInfo {
  avatar: string;
  createTime: Date | string;
  email: string;
  loginIp: string;
  nickName: string;
  phone: string;
  remark: string;
  status: string | number;
  updateTime: Date | string;
  userId: number | string;
  userLevel: number | string;
  userName: string;
}

export const useUserStore = defineStore("user", {
  // 开启数据缓存
  persist: {
    enabled: true,
  },
  state: () => {
    return {
      token: getToken(),
      userinfo: {} as UserInfo,
    };
  },
  getters: {
    isLoggedIn(): any {
      return this.token;
    },
    userInfo(): any {
      return this.userinfo;
    },
    userId(): any {
      return this.userinfo.userId
    }
  },
  actions: {
    login(userInfo: any) {
      const username = userInfo.username.trim();
      const password = userInfo.password.trim();
      const code = userInfo.code.trim();
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        Login.login(username, password, code, uuid)
          .then((res) => {
            console.log(res.code);

            if (res.code !== 200) {
              reject(res.message);
            }
            setToken(res.data);
            // user.value.token = res.data
            this.token = res.data;
            this.getInfo();
            resolve(res);
          })
          .catch((err) => reject(err));
      });
    },
    logout() {
      return new Promise((resolve, reject) => {
        Login.logout()
          .then((res) => {
            // user.value.token = ''
            this.token = "";
            removeToken();
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    getInfo() {
      console.log("getInfo");

      return new Promise((resolve, reject) => {
        Login.getInfo()
          .then((res) => {
            const user = res.data;
            const avatar =
              user.avatar == "" || user.avatar == null
                ? defAva
                : /*import.meta.env.VITE_BASE_URL + */user.avatar;

            this.userinfo = user;
            this.userinfo.avatar = avatar;

            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});
